Insert Data Into A Database Using Core Data Framework

Introduction 

 
In this article, we will learn about Core Data Framework and perform the first step of CRUD operations i.e Creating/Adding data into our database.
 
Before we start, first let's get an overview of the Core Data Framework and the Core Data Stack.
 
Using Core Data we can save our application's permanent data for offline use, to cache temporary data, and to add/undo functionality to our app on a single device. Through Core Data’s Data Model editor, you define your data types and relationships and generate respective class definitions.
 

Core Data Stack

 
A Core Data stack is made up of the following objects: one or more managed object contexts connected to a single persistent store coordinator which then connects to one or more persistent stores. It contains:
  • An instance of NSManagedObjectModel that describes the types, properties,, and relationships of your application. 
  • An instance of NSManagedObjectContext to track the changes in your application's types.
  • An instance of NSPersistentStoreCoordinator used to save and fetch instances of your application's types.
  • An instance of NSPersistentContainer to set up the model, context, and store coordinator simultaneously.
So let's create a simple application that will add our data into the database.
  • Open Xcode and create a new project. Click on iOS -> Single View App.
  • Name your Project, select the language as Swift, and make sure you check the box 'Use Core Data'.
Insert Data Into Database Using Core Data Framework
  • Checking the Use Core Data box will cause Xcode to generate boilerplate code for what’s known as an NSPersistentContainer in AppDelegate.swift.
  • Select the desired location to save your Project.
  • Now, we will design a UI on our Main.storyboard where we will enter the data that we need to insert into our database. I have created a simple UI that will take the name, age, and phone number as input.
Insert Data Into Database Using Core Data Framework
  • Connect the outlets i.e labels,textboxes, and the button to the ViewController. You can do it by opening the Assistant, selecting an outlet, press the Ctrl button, and drag it to your ViewController. Then, name your outlets. 
Insert Data Into Database Using Core Data Framework
  • After creating the UI, open the .xcdatamodeld file in your Project Navigator. You will find the file as 'YourProjectName.xcdatamodeld'.
  • Click on the 'Add Entity' button at the bottom. Name your Entity.
  • Click on the '+' sign in the Attributes section. Name your attributes and assign their types.
  • Refer to the below image.
Insert Data Into Database Using Core Data Framework
  • Next, open your ViewController and paste the following code. Make sure to add the line 'import Core Data'.
    1. import UIKit  
    2. import CoreData  
    3. class ViewController: UIViewController {  
    4.     @IBOutlet weak  
    5.     var txtPhoneNo: UITextField!@IBOutlet weak  
    6.     var txtAge: UITextField!@IBOutlet weak  
    7.     var txtName: UITextField!@IBOutlet weak  
    8.     var lblPhoneNo: UILabel!@IBOutlet weak  
    9.     var lblAge: UILabel!@IBOutlet weak  
    10.     var lblName: UILabel!override func viewDidLoad() {  
    11.         super.viewDidLoad()  
    12.         // Do any additional setup after loading the view.  
    13.     }  
    14.     @IBAction func btnAdd(_ sender: Any) {  
    15.         //1  
    16.         guard  
    17.         let appDelegate = UIApplication.shared.delegate as ? AppDelegate  
    18.         else {  
    19.             return  
    20.         }  
    21.         let managedContext = appDelegate.persistentContainer.viewContext  
    22.         //2  
    23.         let entity = NSEntityDescription.entity(forEntityName: "Details", in : managedContext) !  
    24.             //3  
    25.             let record = NSManagedObject(entity: entity, insertInto: managedContext)  
    26.         //4  
    27.         record.setValue(txtName.text, forKey: "name")  
    28.         record.setValue(Int16(txtAge.text!), forKey: "age")  
    29.         record.setValue(Int16(txtPhoneNo.text!), forKey: "phone")  
    30.         do {  
    31.             try managedContext.save()  
    32.             print("Record Added!")  
    33.             //To display an alert box  
    34.             let alertController = UIAlertController(title: "Message", message: "Record Added!", preferredStyle: .alert)  
    35.             let OKAction = UIAlertAction(title: "OK", style: .default) {  
    36.                 (action: UIAlertAction!) in  
    37.             }  
    38.             alertController.addAction(OKAction)  
    39.             self.present(alertController, animated: true, completion: nil)  
    40.         } catch  
    41.         let error as NSError {  
    42.             print("Could not save. \(error),\(error.userInfo)")  
    43.         }  
    44.     }  

  • Now we are done performing the Add operation.
  • Select a simulator or connect an iPhone device and run your Project.
  • Enter the details and click on the Add button.
  • If you have pasted the above code, then you must get an alert box displaying the message as 'Record Added!'
Insert Data Into Database Using Core Data Framework
  • Also, you can see the same message on your Xcode's output window.
Insert Data Into Database Using Core Data Framework
  • If you get the above outputs, then our data is successfully added to our database!
Hence, we have successfully performed the Create/Add operation. In my next articles, we will perform the remaining CRUD operations.


Similar Articles